const boom = require("boom");

const Pet = require("../models/pet");

const JWTToken = require("../models/token");
const { verifyToken } = require("./../utils/authorization");

const User = require("../models/common");
const Role = require("../models/role");

exports.getPetDetail = async (req, reply) => {
  try {
    const id = req.params.id; // 使用路由参数
    const pet = await Pet.findById(id);
    return reply.send(pet);
  } catch (err) {
    throw boom.boomify(err);
  }
};

exports.addPet = async (req, reply) => {
  try {
    // 确保有文件被上传
    if (!req.files || req.files.length === 0) {
      throw boom.badRequest("至少需要上传一个文件");
    }

    const fileUrls = req.files.map((file) => {
      const { originalname } = file;
      return `${req.protocol}://${req.headers.host}/public/images/${originalname}`;
    });
    // req.body.tags 是一个字符串数组
    const tags = req.body.tags.split(",");
    let postbody = {
      name: req.body.name,
      photoUrls: fileUrls,
      category: req.body.category,
      tags: tags,
      status: req.body.status,
    };
    const pet = new Pet(postbody);
    return pet.save();
  } catch (err) {
    throw boom.boomify(err);
  }
};

exports.putPet = async (req, reply) => {
  try {
    const id = req.params.id;
    const fileUrls = req.files.map((file) => {
      const { originalname } = file;
      return `${req.protocol}://${req.headers.host}/public/images/${originalname}`;
    });
    const tags = req.body.tags.split(",");
    let updatebody = {
      name: req.body.name,
      photoUrls: fileUrls,
      category: req.body.category,
      tags: tags,
      status: req.body.status,
    };
    const update = await Pet.findByIdAndUpdate(id, updatebody, { new: true });
    return update;
  } catch (err) {
    throw boom.boomify(err);
  }
};

exports.deletePet = async (req, reply) => {
  try {
    const id = req.params.id;
    const pet = await Pet.findByIdAndDelete(id);
    return pet;
  } catch (err) {
    throw boom.boomify(err);
  }
};

exports.getPetStatus = async (req, reply) => {
  try {
    const { page = 1, pageSize = 10, status, name, photoUrls, category, tags } = req.query;

    // 构造查询条件对象
    const queryConditions = {};
    if (name) queryConditions.name = new RegExp(name, "i"); // 添加模糊查询，忽略大小写
    if (photoUrls) {
      queryConditions.photoUrls = { $all: photoUrls };
    }
    if (category) queryConditions.category = category;
    if (tags) {
      queryConditions.tags = { $all: tags };
    }
    if (status) queryConditions.status = status;

    const skip = (parseInt(page) - 1) * parseInt(pageSize);

    const petsCount = await Pet.countDocuments(queryConditions); // 计数时使用同样的查询条件

    const petsData = await Pet.find(queryConditions).skip(skip).limit(parseInt(pageSize));

    const responseData = {
      count: petsCount,
      data: petsData,
    };

    return responseData;
  } catch (err) {
    throw boom.boomify(err);
  }
};
